package com.app.controller;

import com.app.model.main.Article;
import com.app.model.main.SystemMessage;
import com.app.model.main.UserInfo;
import com.app.model.response.RetStatus;
import com.app.model.solr.ArticleItem;
import com.app.model.solr.SolrFlag;
import com.app.repository.interfaces.ArticleMapper;
import com.app.repository.interfaces.SystemMessageMapper;
import com.app.repository.interfaces.UserInfoMapper;
import com.app.service.ResponseService;
import com.app.service.SolrService;
import com.app.service.TestService;
import com.app.support.utils.RedisUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lichaojie on 2017/3/8. It's a beautiful day.
 */
@RestController
public class TestController {

    private Log log = LogFactory.getLog(TestController.class);

    @Autowired
    private SystemMessageMapper systemMessageMapper;
    @Autowired
    private TestService testService;
    @Autowired
    private ResponseService responseService;
    @Autowired
    private SolrService solrService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/testtt")
    public RetStatus myy() {
        RetStatus flag = null;
        try {
            flag = testService.test();
            System.out.println(flag);
        }catch (Exception e){

        }finally {
            System.out.println(true);
            return flag;
        }
    }


    public static void main(String[] args){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(df.format(new Date()));
    }


    /**
     * http://localhost:8080/test1?name=
     * @param name
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/test1")
    public String test1(@RequestParam String name)throws Exception{
        String urlString = "http://123.56.29.77:8983/solr/campus-article";
        SolrClient solr = new HttpSolrClient.Builder(urlString).build();

        ArticleItem articleItem = new ArticleItem();
        articleItem.setId(1)
                .setTitle("title1")
                .setLabel("label1,label2,label3")
                .setContent("content1")
                .setType(0);
        solr.addBean(articleItem);

        ArticleItem articleItem1 = new ArticleItem();
        articleItem1.setId(8)
                .setTitle("title8")
                .setLabel("label")
                .setType(0)
                .setContent("Page 1；\n" +
                        "近期工作：（实现外部循环）\n" +
                        " 1.检查退出条件\n" +
                        " 2.每次循环开始自动产生抽象函数和抽象模型\n" +
                        "当前进度：功能基本实现，代码有待优化\n" +
                        "\t图1\n" +
                        "\n" +
                        "Page 2：示例1\n" +
                        "example1.smv原始模型截图\n" +
                        "example1中各变量取值表（取8次） 简要说明：需要验证的属性为真\n" +
                        "\n" +
                        "Page 3：示例1\n" +
                        "运行截图\n" +
                        "\t1.第一次smv的结果，truth value为0，验证失败，循环继续\n" +
                        "\t2.第二次smv的结果，truth value为1，验证成功，退出\n" +
                        "\n" +
                        "Page 4：示例2\n" +
                        "example2.smv原始模型截图\n" +
                        "example2中各变量取值表（取8次） 简要说明：需要验证的属性为假\n" +
                        "\n" +
                        "Page 4：示例2\n" +
                        "运行截图\n" +
                        "\tsmv的结果，truth value为0，checkeset返回false\n" +
                        "\n" +
                        "\n" +
                        "learnabs的截图\n" +
                        "所有函数的介绍 label1,label1,label1");
        solr.addBean(articleItem1);

        ArticleItem articleItem2 = new ArticleItem();
        articleItem2.setId(9)
                .setTitle("title9")
                .setLabel("label1 9")
                .setContent("content9")
                .setType(0);
        solr.addBean(articleItem2);

        for (int i = 10; i <= 30; i ++ ){
            ArticleItem articleItem3 = new ArticleItem();
            articleItem3.setId(i)
                    .setLabel("label1 " + i)
                    .setTitle("title" + i)
                    .setContent("content" + i)
                    .setType(1);
            solr.addBean(articleItem3);
        }

        solr.commit();

        SolrQuery query = new SolrQuery();
        query.setFields("id,label,score"); //控制查询结果返回的域, 等价于query.set("fl", "id,label,score");
        query.set("pf", "id label^50.0 title^10.0 content^10.0");
        //query.set("qf","label");//
        //query.set("cache",false);
        query.set("q", "label");
        //query.set("q.op","AND");
        //query.set("df","label"); //查询条件，此处指查找label项,且只能有一个域

        //query.set("start",0);
        //query.set("rows",10);
        //query.setSort("id", SolrQuery.ORDER.asc);
        QueryResponse response = solr.query(query);

        SolrDocumentList list = response.getResults();
        System.out.println(">>former:\n" + list);
        System.out.println(">>former:\n" + list.get(0));

        //删除后添加的文件
        //solr.deleteById("1");
        //solr.deleteById("8");
//        for(int i = 9 ; i <= 30; i ++){
//            solr.deleteById(i + "");
//        }
        //solr.commit();
        query = new SolrQuery();
        query.set("fl","id,title,score");//控制查询结果返回的域
        query.set("q", "solr page");//查询关键词
        response = solr.query(query);

        list = response.getResults();
        System.out.println(">>later:\n" + list);


        SystemMessage systemMessage = new SystemMessage();
        systemMessage.setMessage("First System Message!!");
        systemMessage.setCreateTime("" + System.currentTimeMillis());
        systemMessage.setIsPushed((byte) 0);
        systemMessageMapper.insert(systemMessage);

        SystemMessage systemMessage1 = new SystemMessage();
        systemMessage1.setId((long) 2);
        systemMessage1.setIsPushed((byte) 1);
        //systemMessage1.setCreateTime("12345678");
        systemMessage1.setMessage("for update testing");
        systemMessageMapper.updateByPrimaryKeySelective(systemMessage1);

//        List<SystemMessage> lists = systemMessageMapper.selectByParam(new SystemMessage());
//        for(SystemMessage systemMessage2 : lists){
//            System.out.println(">>>>>" + systemMessage2.toString());
//        }

        testService.set();
        RetStatus str = testService.get();
        //String str = "testService.get()";

        String result = "Hello " + name + "," + "Welcome to our test1 page! \uF04A" + "\n" + "Redis Test:" + str.getMessage();
        return result;
    }

    /**
     * http://localhost:8080/test2?name=
     * @param name
     * @return
     */
    @RequestMapping(value = "/test2")
    public String test2(String name) throws Exception{
        String urlString = "http://123.56.29.77:8983/solr/campus-article";
        SolrClient solr = new HttpSolrClient.Builder(urlString).build();

        SolrQuery query = new SolrQuery();
        query.setFields("id,label,score"); //控制查询结果返回的域, 等价于query.set("fl", "id,label,score");
        //query.set("cache",false);
        query.set("q", "label1");
        query.set("fq","type:0");
        //query.set("defType","dismax");
        //query.set("pf","id label^50.0 title^10.0 content^10.0");
        //query.set("qf","label");//定义在那些域查询
        query.set("start",0);
        query.set("rows",10);

        QueryResponse response = solr.query(query);

        SolrDocumentList list = response.getResults();
        if (list != null){
            System.out.println(">>former:\n" + list);
            System.out.println(">>former:\n" + list.size());
        }


        //删除后添加的文件
//        solr.deleteById("1");
//        solr.deleteById("8");
//        for (int i = 9 ; i <= 30; i ++){
//            solr.deleteById(i + "");
//        }
//        solr.commit();
        query = new SolrQuery();
        query.set("fq","type:1");
        query.set("fl","id,title,score");//控制查询结果返回的域
        query.set("q", "java redis");//查询关键词
        query.set("start",0);
        query.set("rows",10);

        response = solr.query(query);

        list = response.getResults();
        System.out.println(">>later:\n" + list);

        RetStatus retStatus1 = new RetStatus();
        retStatus1.setCode(200)
                .setMessage("message1")
                .setBody("body1");
        RetStatus retStatus2 = new RetStatus();
        retStatus2.setCode(202)
                .setMessage("message2")
                .setBody("body2");
        List<RetStatus> list1 = new ArrayList<>();
        list1.add(retStatus1);
        list1.add(retStatus2);
        RetStatus retStatus3 = new RetStatus();
        retStatus3.setCode(204)
                .setMessage("message3")
                .setBody(list1);

        RetStatus str = testService.get();
        String result = "Hello " + name + "," + "Welcome to our test2 page! \uF04A" + "\n" + "Redis Test:" + str.getMessage();


        if(name.equals("kristy")){
            for (int i = 0 ; i <= 300; i ++){
                solrService.delete(Integer.toString(i), SolrFlag.ARTICLE);
                solrService.delete(Integer.toString(i),SolrFlag.USER);
            }
            for (long i = 1; i <= articleMapper.getMaxId(); i ++){
                Article article = articleMapper.selectByPrimaryKey(i);
                if(article.getFlag() == 1){
                    solrService.addField(article);
                }
            }
            for (long i = 1; i <= userInfoMapper.getMaxId(); i ++){
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(i);
                solrService.addField(userInfo);
            }

        }


        return result;
    }

    @RequestMapping(value = "/console/delete",method = RequestMethod.GET)
    public String delete(@RequestParam Long id,
                         @RequestParam Integer type){
        boolean flag;

        if(type == 0){
            flag = solrService.delete(Long.toString(id), SolrFlag.ARTICLE);
        }else {
            flag = solrService.delete(Long.toString(id), SolrFlag.USER);
        }

        if(flag){
            return "SUCCESS";
        }else {
            return "FAIL";
        }
    }

    @RequestMapping(value = "/console/deleteAllArticle")
    public String deleteAllArticle(){
        for (long i = 1; i <= articleMapper.getMaxId(); i ++){
            Article article = articleMapper.selectByPrimaryKey(i);
            if(article != null && article.getFlag() == 1){
                solrService.delete(Long.toString(i),SolrFlag.ARTICLE);
            }
        }

        return "deleteAlArticle Done.";
    }

    @RequestMapping(value = "/console/deleteAllUser")
    public String deleteAllUser(){
        for (long i = 1; i <= userInfoMapper.getMaxId(); i ++){
            solrService.delete(Long.toString(i),SolrFlag.USER);
        }

        return "deleteAllUser Done.";
    }

    @RequestMapping(value = "/console/deleteAll")
    public String deleteAll(){
        deleteAllArticle();
        deleteAllUser();

        return "deleteAll Done";
    }

    @RequestMapping(value = "/console/addAllArticle")
    public String addAllArticle(){
        for (long i = 1; i <= articleMapper.getMaxId(); i ++){
            Article article = articleMapper.selectByPrimaryKey(i);
            if(article!= null && article.getFlag() == 1){
                solrService.addField(article);
            }
        }

        return "addAllArticle Done.";
    }

    @RequestMapping(value = "/console/addAllUser")
    public String addAllUser(){
        for (long i = 1; i <= userInfoMapper.getMaxId(); i ++){
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(i);
            if(userInfo != null){
                solrService.addField(userInfo);
            }
        }

        return "addAllUser Done.";
    }

    @RequestMapping(value = "/console/addAll")
    public String addAll(){
        addAllArticle();
        addAllUser();

        return "addAll Done";
    }

    @RequestMapping(value = "/testCoding" ,produces = "application/json;charset=utf-8")
    public RetStatus testCoding(){
        return responseService.doResponse(100);
    }

    @RequestMapping(value = "/search-testing")
    public RetStatus searchTesting() throws Exception{
        String urlString = "http://123.56.29.77:8983/solr/campus-article";
        SolrClient solr = new HttpSolrClient.Builder(urlString).build();

        SolrQuery query = new SolrQuery();
        query.set("q", "帖子");
        query.setFields("*,score"); //控制查询结果返回的域, 等价于query.set("fl", "id,label,score");
        //query.set("fq","type:0");
        //query.set("defType","dismax");
        //query.set("pf", "label^5.0");
        query.set("qf","label");//
        //query.set("cache",false);
        //query.set("q.op","AND");
        //query.set("df","label"); //查询条件，此处指查找label项,且只能有一个域

        //query.set("start",0);
        //query.set("rows",10);
        //query.setSort("id", SolrQuery.ORDER.asc);

        query.set("start", 0);
        query.set("rows",10);

        QueryResponse response = solr.query(query);

        SolrDocumentList list = response.getResults();
        if (list != null){
            //System.out.println(">>former:\n" + list);
            for (SolrDocument solrDocument : list){
                System.out.println(solrDocument);
            }
            System.out.println(">>former:\n" + list.size());
        }

        RetStatus retStatus = new RetStatus();
        //retStatus.setBody(list);
        return retStatus;
    }


}
